package ue.web;

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import java.util.HashMap;

import org.apache.commons.io.FileUtils;
import org.apache.commons.lang.ArrayUtils;

import ue.util.StringHelper;

/**
 * 静态页面处理
 * @author Glacier
 * 
 */
public class SPage
{
    private final byte[] m_btBOM = new byte[]
    { (byte) 0xEF, (byte) 0xBB, (byte) 0xBF };

    private String m_strSavePath;

    private String m_strContentPath;

    public SPage(String strSavePath, String strContentPath)
    {
        m_strSavePath = strSavePath;
        m_strContentPath = strContentPath;
    }

    public SPage()
    {
//        m_strSavePath = Config.ApplicationPath + "history" + File.separator;
//        m_strContentPath = Config.ContextPath;
    }

    /**
     * 获得页面的内容
     * @param strURL 页面地址
     * @param strSaveFileName 保存的文件名
     * @param strSaveEncoding 编码
     * @return StringBuffer
     * @throws IOException
     */
    public StringBuffer getHTML(String strURL, String strSaveFileName, String strSaveEncoding) throws IOException
    {
        InputStreamReader isr = null;
        BufferedReader in = null;
        InputStream inStream = null;
        try
        {
            URL url = new URL(strURL);
            // 每次open都创建一个新的实例 注意：这里实际没有连接
            URLConnection urlConnection = url.openConnection();

            // getInputStream将会调用connect操作
            inStream = urlConnection.getInputStream();
            isr = new InputStreamReader(inStream, strSaveEncoding);
            in = new BufferedReader(isr);
            String strInputLine;
            StringBuffer sb = new StringBuffer();
            while ((strInputLine = in.readLine()) != null)
            {
                sb.append(strInputLine + "\r\n");
            }
            return sb;
        }
        catch (Exception e)
        {
//            LogManager.error(e);
            return null;
        }
        finally
        {
            // 注意关闭顺序 先关闭BufferedReader 再关闭InputStreamReader 最后关闭InputStream
            if (in != null)
            {
                in.close();
            }
            if (isr != null)
            {
                isr.close();
            }
            if (inStream != null)
            {
                inStream.close();
            }

        }
    }

    /**
     * 处理该页面
     * @param strURL
     * @param strCharacterEncoding
     * @param bOverWrite
     * @param sb
     * @return
     * @throws IOException
     */
    public String process(String strURL, String strCharacterEncoding, boolean bOverWrite, StringBuffer sb)
            throws IOException
    {
        return process(strURL, "shtml", strCharacterEncoding, bOverWrite, sb, false, null);
    }

    /**
     * <生成静态页面> <功能详细描述>
     * @param strURL 网站地址
     * @param fileName 文件名,不带后缀,后缀默认以html结尾
     * @param strCharacterEncoding 字符集
     * @param bOverWrite 重写,默认重写
     * @param sb 传入的sb
     * @return
     * @throws IOException [参数说明]
     * 
     * @return String [返回类型说明]
     * @exception throws [违例类型] [违例说明]
     * @see [类、类#方法、类#成员]
     */
    public String process(String strURL, String fileName, String strCharacterEncoding, boolean bOverWrite,
            boolean bBOM, StringBuffer sb) throws IOException
    {
        return process(strURL, fileName, "html", strCharacterEncoding, bOverWrite, sb, bBOM, null);
    }

    public String process(String strURL, String strExtName, String strCharacterEncoding, boolean bOverWrite,
            StringBuffer sb, boolean bBOM, HashMap<String, String> map) throws IOException
    {
        String strFileName = "", strQuery = null;
        int intBPos = strURL.lastIndexOf('/');
        if (intBPos < 0)
            return null;
        int intEPos = strURL.indexOf('.', intBPos);
        if (intEPos < 0)
            return null;
        strFileName = strURL.substring(intBPos + 1, intEPos);
        intEPos = intBPos + 1;
        if (strURL.indexOf("?") > 0)
        {
            strQuery = strURL.substring(strURL.indexOf("?") + 1);
        }
        if (strQuery != null)
        {
            String[] arr = strQuery.split("&");
            for (int i = 0; i < arr.length; i++)
            {
                String[] _arr = arr[i].split("=");
                String strValue = _arr.length > 0 ? _arr[1] : "";
                strFileName = StringHelper.linkString(strFileName, "-", strValue);
            }
        }
        strFileName += "." + strExtName;
        int intPos = strURL.indexOf(m_strContentPath);
        if (intPos > 0)
        {
            intBPos = intPos + m_strContentPath.length();
            strFileName = strURL.substring(intBPos, intEPos) + strFileName;
            return process(strURL, strFileName, strExtName, strCharacterEncoding, bOverWrite, sb, bBOM, map);
        }
        return null;
    }

    public String process(String strURL, String fileName, String strExtName, String strCharacterEncoding,
            boolean bOverWrite, StringBuffer sb, boolean bBOM, HashMap<String, String> map) throws IOException
    {
        String strFileName = "";
        // 还没有后缀,则+后缀
        if (!fileName.endsWith("." + strExtName))
        {
            strFileName = fileName + "." + strExtName;
        }
        else
        {
            strFileName = fileName;
        }
        String strSaveFileName = (m_strSavePath + strFileName).replace("/", File.separator);
        if (strSaveFileName.indexOf(File.separator) == 0)
            strSaveFileName = strSaveFileName.substring(1);
//        LogManager.debug("静态页面路径在:" + strSaveFileName);

        if (!bOverWrite)
        {
            File f = new File(strSaveFileName);
            if (f.exists())
                return strFileName;
        }
        String strConnectionURL = strURL.replaceAll("\\.(" + strExtName + ")", ".jsp");
        StringBuffer sbHTML = getHTML(strConnectionURL, strSaveFileName, strCharacterEncoding);
        if (sbHTML != null)
        {
            if (map != null)
            {
                String strHTML = sbHTML.toString();
                for (String key : map.keySet())
                {
                    strHTML = strHTML.replace("$" + key + "$", map.get(key));
                }
                sb.append(strHTML);
            }
            else
            {
                sb.append(sbHTML);
            }
            File file = new File(strSaveFileName);
            if (bBOM)
            {
                byte[] data = ArrayUtils.addAll(m_btBOM, sb.toString().getBytes("utf-8"));
                FileUtils.writeByteArrayToFile(file, data);
            }
            else
            {
                FileUtils.writeStringToFile(file, sb.toString(), "utf-8"); // strSaveEncoding
            }
            return strFileName;
        }

        return null;
    }

    public static void main(String[] args) throws IOException
    {
        StringBuffer sb = new StringBuffer();
        SPage page = new SPage("E:/", "1951");
        String url1 = "http://www.aceona.com/myaceona/careerinfo/check.do?corpID=1951&jobID=13783";
        String url2 = "http://q.aceona.com/azone/bzone/index.jsp?group_id=999000001275348655295249&";
        // String strFileName =
        // page.process("http://www.aceona.com/myaceona/careerinfo/check.do?corpID=1951&jobID=13783",
        // "utf-8", Boolean.TRUE, sb);
        String strFileName1 = page.process(url1, "1951/13783", "utf-8", true, true, sb);
//        String strFileName2 = page.process(url2, "utf-8", true, sb);
        System.out.print(strFileName1);
//        System.out.print(strFileName2);
    }
}
